package com.li.commons.util;

public class CookieAuthUtil {
	
	/**
	 * cookie加密工具
	 * @param encodeStr   加密字符串
	 * @param privateKey  密钥
	 * @return
	 */
	public static String authEncode(String encodeStr, String privateKey) {
		String key = MD5.compute(privateKey);
		int keyLength = key.length();
		encodeStr = MD5.compute(encodeStr + key).substring(0, 8) + encodeStr;
		int stringLength = encodeStr.length();
		String result = "";
		int[] rndKey = new int[256];
		int[] box = new int[256];

		for (int i = 0; i <= 255; i++) {
			rndKey[i] = (int) key.charAt(i % keyLength);
			box[i] = i;
		}

		for (int j = 0, i = 0; i < 256; i++) {
			j = (j + box[i] + rndKey[i]) % 256;
			int tmp = box[i];
			box[i] = box[j];
			box[j] = tmp;
		}

		for (int a = 0, j = 0, i = 0; i < stringLength; i++) {
			a = (a + 1) % 256;
			j = (j + box[a]) % 256;
			int tmp = box[a];
			box[a] = box[j];
			box[j] = tmp;
			int ascCode = ((int) (encodeStr.charAt(i)))
					^ (box[(box[a] + box[j]) % 256]);
			result = result + ((char) ascCode + "");
		}
		//原算法删除了=补位,这里不错删除
		return EncodeUtil.encodeBase64(result);
	}

	/**
	 * cookie解密工具
	 * @param decodeString 需解密字符串
	 * @param privateKey   密钥
	 * @return
	 */
	public static String authDeCode(String decodeString, String privateKey) {
		String key = MD5.compute(privateKey);
		int keyLength = key.length();
		decodeString = EncodeUtil.decodeBase64(decodeString);
		System.out.println("base64解密:"+decodeString);
		int stringLength = decodeString.length();
		String result = "";
		int[] rndKey = new int[256];
		int[] box = new int[256];
		for (int i = 0; i <= 255; i++) {
			rndKey[i] = (int) key.charAt(i % keyLength);
			box[i] = i;
		}
		
		for (int j = 0, i = 0; i < 256; i++) {
			j = (j + box[i] + rndKey[i]) % 256;
			int tmp = box[i];
			box[i] = box[j];
			box[j] = tmp;
		}

		for (int a = 0, j = 0, i = 0; i < stringLength; i++) {
			a = (a + 1) % 256;
			j = (j + box[a]) % 256;
			int tmp = box[a];
			box[a] = box[j];
			box[j] = tmp;
			int ascCode = ((int) (decodeString.charAt(i))) ^ (box[(box[a] + box[j]) % 256]);
			result = result + ((char) ascCode + "");
		}

		if (result.substring(0, 8).equals(MD5.compute(result.substring(8) + key).substring(0, 8))) {
			return result.substring(8);
		} else {
			return "";
		}
	}

	public static void main(String args[]) {
		String key = "keyikongjian&*()Login";
		String authStr = authDeCode("DwPDkMO4EMKTw6rDq3YAw5DCqgoTwpjCnAA3N8Kqb8O0w5AwwqsBLwjDhcKwX8OEwqcHwonChWTCt8KSNMKjXsKXRMKNcijDqy", key);
		System.out.println("authStr==================" + authStr);
		System.out.println("decode str="+authDeCode(authStr, key));
	}
}
